package com.juno.cafenoa;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TabHost;

import com.juno.cafenoa.cart.Cart;
import com.juno.cafenoa.event.EventActivity;
import com.juno.cafenoa.introduce.CafeIntroActivity;
import com.juno.cafenoa.menu.Category;
import com.juno.cafenoa.menu.CategoryBasicItem;
import com.juno.cafenoa.menu.MenuBasicItem;
import com.juno.cafenoa.mypage.MyPage;
import com.juno.cafenoa.net.AsyncTaskCompleteListener;
import com.juno.cafenoa.net.HttpPostTask;
import com.juno.cafenoa.sqlite.CafeNoaDBAdapter;
import com.juno.cafenoa.util.CafeNoaPreference;
import com.juno.cafenoa.util.Util;

public class MainActivity extends TabActivity {
	Context mContext;
	TabHost tabHost;
	ProgressBar pb;
	
	public SQLiteDatabase db;
	private CafeNoaDBAdapter dbAdapter;

	public static ExecutorService executor = Executors.newCachedThreadPool();
	ArrayList<MenuBasicItem> mList;
	ArrayList<CategoryBasicItem> cList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		mContext = this;
		pb = new ProgressBar(mContext);
		pb.setVisibility(View.GONE);
		
		//tabhost에 activity 추가.
		//home은 invisible.
		tabHost = getTabHost();
		tabHost.addTab(tabHost.newTabSpec("HOME").setIndicator("소개", getResources().getDrawable(R.drawable.host_icon_home)).setContent(new Intent(this, MainView.class)));
		tabHost.addTab(tabHost.newTabSpec("소개").setIndicator("소개", getResources().getDrawable(R.drawable.host_icon_home)).setContent(new Intent(this, CafeIntroActivity.class)));
		tabHost.addTab(tabHost.newTabSpec("주문").setIndicator("주문", getResources().getDrawable(R.drawable.host_icon_order)).setContent(new Intent(this, Category.class)));
		tabHost.addTab(tabHost.newTabSpec("카트").setIndicator("카트", getResources().getDrawable(R.drawable.host_icon_cart)).setContent(new Intent(this, Cart.class)));
		tabHost.addTab(tabHost.newTabSpec("이벤트").setIndicator("이벤트", getResources().getDrawable(R.drawable.host_icon_event)).setContent(new Intent(this, EventActivity.class)));
		tabHost.addTab(tabHost.newTabSpec("MY").setIndicator("MY", getResources().getDrawable(R.drawable.host_icon_mypage)).setContent(new Intent(this, MyPage.class)));
		getTabHost().getTabWidget().getChildAt(0).setVisibility(View.GONE);
		
		if(getIntent().getBooleanExtra(Constants.NOTIFICATION_START, false))
			tabHost.setCurrentTab(4);
		else 
			tabHost.setCurrentTab(0);
		
		if(!CafeNoaPreference.getRegistState(mContext)){
			pb.setVisibility(View.VISIBLE);
			mList = new ArrayList<MenuBasicItem>();
			cList = new ArrayList<CategoryBasicItem>();
			dbAdapter = new CafeNoaDBAdapter();
			getCategoryListener.excuteHttpTask();
		}
	}
	
	AsyncTaskCompleteListener getCategoryListener = new AsyncTaskCompleteListener(){

		@Override
		public void excuteHttpTask() {
			//Url 세팅.
			String url = Util.getUrl("CafeCategoryGet");
			
			//name value pair에 id와 password 세팅
			ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
			value.add(new BasicNameValuePair("REQUEST_CAFE_ID", "1"));
			
			//httpPostTast 실행.
			HttpPostTask http = new HttpPostTask(mContext, value, url, getCategoryListener);
			http.execute();
		}

		@Override
		public void onTaskComplete(String result, boolean taskOk) {
			//http 통신 실행후 서버로부터 오는 내용.
			//작업이 모두 완료되었다면.
			Log.v("result","reuslt :" + result);
			if(taskOk){
				int code = -1;
				
				try {
					JSONObject object = new JSONObject(result);
					code = object.getInt("RESULT");

					if(code==Constants.NETWORK_SUCCESS){
						JSONArray jArr = object.getJSONArray("ITEM");
						
						int id = -1;
						String name = null;
						
						for(int i=0;i<jArr.length();i++){
							JSONObject obj = jArr.getJSONObject(i);
							id = obj.getInt("CATEGORY_ID");
							name = obj.getString("CATEGORY_NAME");						
							cList.add(new CategoryBasicItem(id, name));
						}
						//DB에 저장하는 루틴 추가.
						getMenuListener.excuteHttpTask();
					} else {
						Log.e("CAFE_NOA","Server Error on :" + code);
						onErrorServer();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		
	};
	
	
	AsyncTaskCompleteListener getMenuListener = new AsyncTaskCompleteListener(){

		@Override
		public void excuteHttpTask() {
			//Url 세팅.
			String url = Util.getUrl("CafeMenuGet");
			
			//name value pair에 id와 password 세팅
			ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
			value.add(new BasicNameValuePair("REQUEST_CAFE_ID", "1"));
			
			//httpPostTast 실행.
			HttpPostTask http = new HttpPostTask(mContext, value, url, getMenuListener);
			http.execute();
		}

		@Override
		public void onTaskComplete(String result, boolean taskOk) {
			//http 통신 실행후 서버로부터 오는 내용.
			//작업이 모두 완료되었다면.
			Log.v("result","reuslt :" + result);
			if(taskOk){
				int code = -1;
				
				try {
					JSONObject object = new JSONObject(result);
					code = object.getInt("RESULT");

					if(code==Constants.NETWORK_SUCCESS){
						JSONArray jArr = object.getJSONArray("ITEM");
						
						String id = null;
						int category = -1;
						String name = null;
						int price = -1;
						String imageUrl = null;
						String content = null;
						String option = null;
						
						for(int i=0;i<jArr.length();i++){
							JSONObject obj = jArr.getJSONObject(i);
							id = obj.getString("PRODUCT_ID");
							category = obj.getInt("PRODUCT_CATE_ID");
							name = obj.getString("PRODUCT_NAME");
							price = obj.getInt("PRODUCT_PRICE");
							imageUrl = obj.getString("PRODUCT_IMG");
							content = obj.getString("PRODUCT_CONTENT");
							option = obj.getString("PRODUCT_OPTION");
						
							mList.add(new MenuBasicItem(mContext, Integer.valueOf(id), category, name, price, imageUrl, content, option));
						}
						//DB에 저장하는 루틴 추가.
						setDB();
					} else {
						Log.e("CAFE_NOA","Server Error on :" + code);
						
						onErrorServer();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		
	};
	
	public void setDB(){
		dbAdapter.open(mContext);

		for(int i=0;i<cList.size();i++){
			Log.v("insert","data : " + cList.get(i).getId());
			dbAdapter.insertCategoryData(cList.get(i).getId(), cList.get(i).getName());
		}
		
		for(int i=0;i<mList.size();i++){
			Log.v("insert","data : " + mList.get(i).getProductNumber());
			dbAdapter.insertMenuData(mList.get(i).getProductNumber(), mList.get(i).getParentCategoryNumber(), mList.get(i).getProductName(), mList.get(i).getPrice(), mList.get(i).getImgUrl(), mList.get(i).getProductDetailInfo(), mList.get(i).getProductOption());
		}
		dbAdapter.Close();
		//모든 과정이 전부 끝남.
		pb.setVisibility(View.GONE);
		
		CafeNoaPreference.setRegistState(mContext, true);
		
//		Intent intent = new Intent(this, MainActivity.class);
//		startActivity(intent);
//		finish();
	}
	
	public void onErrorServer(){
		AlertDialog.Builder ab = new AlertDialog.Builder(this);
		ab.setTitle("안내");
		ab.setMessage("서버 점검중입니다.\n일부 기능은 제한될수 있습니다.");
		ab.setPositiveButton("확인", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
			}
		});
		AlertDialog ad = ab.create();
		ad.show();
	}
}
